const app = getApp();

Page({
  data: {
    tabs: [
      { id: 0, name: "全部" },
      { id: 1, name: "待付款" },
      { id: 2, name: "待发货" },
      { id: 3, name: "待收货" },
      { id: 4, name: "已完成" }
    ],
    activeTab: 0,
    orderList: [],
    page: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    isEmpty: false
  },

  onLoad: function (options) {
    // 从其他页面跳转过来时可能指定显示哪个标签
    if (options.status) {
      this.setData({
        activeTab: parseInt(options.status)
      });
    }
    
    this.loadOrderList(true);
  },

  onShow: function () {
    // 如果从其他页面返回，可能需要刷新数据
    if (this.data.needRefresh) {
      this.setData({
        page: 1,
        hasMore: true,
        orderList: []
      });
      this.loadOrderList(true);
      this.data.needRefresh = false;
    }
  },

  // 切换标签
  onTabChange: function (e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.activeTab === index) return;
    
    this.setData({
      activeTab: index,
      page: 1,
      orderList: [],
      hasMore: true
    });
    
    this.loadOrderList(true);
  },

  // 加载订单列表
  loadOrderList: function (refresh = false) {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({ loading: true });
    
    // 从本地存储获取订单数据
    let userOrders = wx.getStorageSync('userOrders') || [];
    console.log('从本地存储获取订单数据:', userOrders);
    
    // 根据当前选中的标签过滤订单
    let filteredOrders = userOrders;
    if (this.data.activeTab > 0) {
      const statusMap = {
        1: '待付款',
        2: '待发货',
        3: '待收货',
        4: '已完成'
      };
      const targetStatus = statusMap[this.data.activeTab];
      filteredOrders = userOrders.filter(order => order.status === targetStatus);
    }
    
    // 分页处理 - 直接使用真实订单数据
    let hasMore = false; // 本地数据没有分页，一次性加载所有
    
    // 设置空状态
    if (filteredOrders.length === 0) {
      this.setData({
        isEmpty: true,
        loading: false,
        hasMore: false,
        orderList: []
      });
      return;
    }
    
    this.setData({
      orderList: refresh ? filteredOrders : this.data.orderList.concat(filteredOrders),
      page: 1, // 本地数据无需分页
      loading: false,
      isEmpty: filteredOrders.length === 0,
      hasMore: false // 一次性加载所有数据
    });
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.setData({
      page: 1,
      hasMore: false,
      orderList: []
    });
    
    this.loadOrderList(true);
    wx.stopPullDownRefresh();
  },
  
  // 上拉加载更多 - 本地数据不需要分页加载
  onReachBottom: function () {
    // 不再需要加载更多，一次性加载所有数据
    console.log('所有订单数据已加载完成');
  },
  
  // 去支付
  goPay: function (e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showToast({
      title: '前往支付页面',
      icon: 'none'
    });
    // 实际跳转到支付页面
    // wx.navigateTo({
    //   url: `/pages/payment/payment?orderId=${orderId}`
    // });
  },
  
  // 查看物流
  viewLogistics: function (e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showToast({
      title: '查看物流信息',
      icon: 'none'
    });
    // 实际跳转到物流页面
    // wx.navigateTo({
    //   url: `/pages/logistics/logistics?orderId=${orderId}`
    // });
  },
  
  // 确认收货
  confirmReceive: function (e) {
    const orderId = e.currentTarget.dataset.id;
    const that = this;
    
    wx.showModal({
      title: '确认收货',
      content: '确认已收到该订单商品吗？',
      success: function (res) {
        if (res.confirm) {
          // 调用确认收货接口
          wx.showLoading({ title: '处理中...' });
          
          // 更新订单状态
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '确认收货成功',
              icon: 'success'
            });
            
            that.updateOrderStatus(orderId, '已完成');
          }, 500);
        }
      }
    });
  },
  
  // 去评价
  goReview: function (e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showToast({
      title: '前往评价页面',
      icon: 'none'
    });
    // 实际跳转到评价页面
    // wx.navigateTo({
    //   url: `/pages/review/review?orderId=${orderId}`
    // });
  },
  
  // 取消订单
  cancelOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;
    const that = this;
    
    wx.showModal({
      title: '取消订单',
      content: '确认取消该订单吗？',
      success: function (res) {
        if (res.confirm) {
          // 调用取消订单接口
          wx.showLoading({ title: '处理中...' });
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // 更新订单状态
            that.updateOrderStatus(orderId, '已取消');
          }, 500);
        }
      }
    });
  },
  
  // 删除订单
  deleteOrder: function (e) {
    const orderId = e.currentTarget.dataset.id;
    const that = this;
    
    wx.showModal({
      title: '删除订单',
      content: '确认删除该订单吗？删除后不可恢复',
      success: function (res) {
        if (res.confirm) {
          // 调用删除订单接口
          wx.showLoading({ title: '处理中...' });
          
          // 从本地存储中删除订单
          let userOrders = wx.getStorageSync('userOrders') || [];
          const newUserOrders = userOrders.filter(order => order.id !== orderId);
          wx.setStorageSync('userOrders', newUserOrders);
          
          // 从列表中移除该订单
          const newOrderList = that.data.orderList.filter(order => order.id !== orderId);
          
          setTimeout(() => {
            wx.hideLoading();
            wx.showToast({
              title: '订单已删除',
              icon: 'success'
            });
            
            that.setData({
              orderList: newOrderList,
              isEmpty: newOrderList.length === 0
            });
          }, 500);
        }
      }
    });
  },
  
  // 查看订单详情
  goOrderDetail: function (e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${orderId}`
    });
  },
  
  // 再次购买
  buyAgain: function (e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
    // 实际调用加入购物车接口
  },
  
  // 去购物
  goShopping: function () {
    wx.switchTab({
      url: '/pages/home/home'
    });
  },
  
  // 更新订单状态（本地更新）
  updateOrderStatus: function (orderId, newStatus) {
    // 更新页面显示的订单列表
    const orderList = this.data.orderList.map(order => {
      if (order.id === orderId) {
        return {
          ...order,
          status: newStatus
        };
      }
      return order;
    });
    
    // 更新本地存储中的订单数据
    let userOrders = wx.getStorageSync('userOrders') || [];
    const updatedUserOrders = userOrders.map(order => {
      if (order.id === orderId) {
        return {
          ...order,
          status: newStatus
        };
      }
      return order;
    });
    wx.setStorageSync('userOrders', updatedUserOrders);
    
    this.setData({ orderList });
  }
}); 